package br.com.consultsystems.persistencia.impl.financeiro;

import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import br.com.consultsystems.dominio.financeiro.Classe;
import br.com.consultsystems.persistencia.spec.AbstractAdministradoraRepository;
import br.com.consultsystems.persistencia.spec.financeiro.ClassePersistencia;

@Stateless(name = "classePersistencia")
public class ClassePersistenciaImpl extends
		AbstractAdministradoraRepository<Classe> implements
		ClassePersistencia {

	protected ClassePersistenciaImpl() {
		super(Classe.class);
	}

	@Override
	public List<Classe> retrieveAll() {
		return retrieveByCriteria(null);
	}

	@Override
	public List<Classe> retrieveByClasse(String nome) throws Exception {

		final EntityManager em = getEntityManager();
		final CriteriaBuilder criteriaBuilder = createCriteriaBuilder();
		final CriteriaQuery<Classe> criteriaQuery = createCriteriaQuery(criteriaBuilder);
		final Root<Classe> root = createRoot(criteriaQuery);
		
		/* Repository -> Apenas pesquias as informações no banco de dados
		 * Filtro por codigo */
		final Path<String> pathClasse = root.get("nome");
		final Predicate predicateClasse = criteriaBuilder.like(pathClasse, "%"+nome+"%");

		criteriaQuery.where(predicateClasse);
		criteriaQuery.orderBy(criteriaBuilder.asc(pathClasse));
		
		final TypedQuery<Classe> typedQuery = em.createQuery(criteriaQuery);
		return typedQuery.getResultList();
	}

}
